<template>
  <div style="margin: 20px" />
  <el-form label-width="auto" :model="operInfo" style="max-width: 600px">
    <el-form-item label="登录账号">
      <el-input v-model="operInfo.adminname" class="myInput" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input type="password" v-model="operInfo.password" />
    </el-form-item>
    <el-form-item label="角色">
      <el-select v-model="operInfo.role">
        <el-option value="1" label="超级管理员"></el-option>
        <el-option value="2" label="轮播图维护人员"></el-option>
        <el-option value="3" label="商品维护人员"></el-option>
        <el-option value="4" label="售后人员"></el-option>
      </el-select>
    </el-form-item>
    <el-tree
      ref="treeRef"
      style="max-width: 600px"
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
    />

    <el-form-item>
      <el-button class="loginBtn" type="primary" @click="editOper">
        修改
      </el-button>
      <el-button class="loginBtn" type="primary" @click="cancelFn">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>
  
  <script lang="ts" setup>
import { reactive, defineEmits, defineProps, watch, ref } from "vue";
// import { useRouter } from "vue-router";
import { ElMessage, ElTree } from "element-plus";
import type { TreeKey } from "element-plus";
import { Modificationapi, getOperDetailApi } from "@/api/management";
import type { IOper } from "@/myTypes";
import data from "./menudData";

const treeRef = ref<InstanceType<typeof ElTree>>();

// 声明属性
const props = defineProps<{
  adminname: string;
}>();

// 声明事件
const emit = defineEmits<{
  (e: "closeWin", isRefresh: boolean): void;
}>();
//在组合式api中，如果想要拿到路由对象，使用hooks ，useRouter

const operInfo = reactive<IOper>({
  adminname: "",
  password: "",
  role: "",
  checkedKeys: [],
});

// 获取当前操作人员的信息（要修改的信息）；
async function getOperDetail() {
  const res = await getOperDetailApi(props.adminname);
  if (res.data.code === "200") {
    const { adminname, role, checkedKeys } = res.data.data;
    operInfo.adminname = adminname;
    operInfo.role = String(role);
    console.log("JSON.parse(checkedKeys[0])", JSON.parse(checkedKeys[0]));
    operInfo.checkedKeys = JSON.parse(checkedKeys[0]);
    treeRef.value!.setCheckedKeys(
      operInfo.checkedKeys as Array<TreeKey>,
      false
    );
  }
}

watch(props, () => getOperDetail(), { immediate: true });

// 修改操作人员
const editOper = () => {
  operInfo.checkedKeys = JSON.stringify(treeRef.value!.getCheckedKeys(false));

  Modificationapi(operInfo).then((res) => {
    if (res.data.code === "200") {
      ElMessage.success("修改成功！");
      // operInfo.adminname=""
      operInfo.password = "";
      // operInfo.role=""
      emit("closeWin", true);
    }
  });
};

// 取消：
const cancelFn = () => {
  emit("closeWin", false);
};
</script>
  
  <style scoped lang="scss"></style>
  